#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''

import logging
import LoginFactory
from pycommon import Pack as packet
from pycommon import Const
from twisted.internet import task
import CenterBuild
import json

ENCODING = u"UTF-8"
import ServerConfig
class TmpGate(object):
    def __init__(self,sid,ip,port):
        self.sid = sid
        self.ip = ip
        self.port = port
        self.online = 0

    def parse(self,js):
        jsObject = json.loads(js)
        self.sid = jsObject.get('sid')
        self.ip = jsObject.get('ip')
        self.port = jsObject.get('port')

    def setOnline(self,num):
        self.online = num

class GateManager(object):
    def __init__(self):
        self.gateMap = {};

    def start(self,interval):
        l = task.LoopingCall(self.onTimer)
        l.start(interval, False)

    def onTimer(self):
        self.doTask()

    def updateGateData(self):
        gateInfoJson = self.getGateInfoJson()
        LoginFactory.instance.broadcast(CenterBuild.gateUpdate())

    def doTask(self):
        self.updateGateData()

    def gateLogin(self,sid,ip,port):
        tg = TmpGate(sid,ip,port)
        if self.gateMap.get(sid,None) == None:
            self.gateMap[sid] = tg
            logging.debug(u"gateid=%d ip=%s port=%d online=%d register sucess",tg.sid,tg.ip,tg.port,tg.online)
            self.updateGateData()
        else:
            logging.debug(u"gateid=%d register error",sid)
        
    def gateLogout(self,sid):
        if self.gateMap.get(sid,None) != None:
            tg = self.gateMap.pop(sid)
            logging.debug(u"gateid=%d ip=%s port=%d exit sucess",tg.sid,tg.ip,tg.port)
            self.updateGateData()
        else:
            logging.debug(u"gateid=%d exit error",sid);
      
    def getGateInfoJson(self):
        sendDic = {}
        for key in self.gateMap:
           tg = self.gateMap.get(key)
           sendDic[tg.sid] = {"sid":tg.sid,"ip":tg.ip,"port":tg.port,"online":tg.online}
        return json.dumps(sendDic).encode(ENCODING)
    
      
    def checkGateSidValid(self,sid):
        if self.gateMap.get(sid,None) == None:
            return True
        return False

    def updateOnline(self,sid,count):
        if self.gateMap.get(sid,None) != None:
            tg = self.gateMap.get(sid)
            tg.online = count
        else:
            logging.debug(u"gateid=%d updateOnline error",sid);

instance = GateManager()